import { defineStore } from 'pinia'
import { Ref, nextTick, toRaw } from 'vue'
export const useSettingStore = defineStore('setting', {
    state: () => ({
        isCollapse: localStorage.getItem('menuCollapse') === 'true' ? true : false,
        isExpanded: localStorage.getItem('departmentlist') === 'true' ? true : false, // 部门展开状态
        departmentRef: null as any // 明确类型声明
    }),
    actions: {
        setCollapse(isCollapse: boolean) {
            this.isCollapse = isCollapse
        },
        toggleCollapse() {
            this.isCollapse = !this.isCollapse
            localStorage.setItem('menuCollapse', this.isCollapse.toString())
        },
        setDepartmentRef(ref: any) {
            this.departmentRef = ref
            console.log('Store收到表格引用:', !!this.departmentRef)
        },
        toggleAllExpansion() {
            if (!this.departmentRef){
                console.log("1111"); 
                return
            }

            this.isExpanded = !this.isExpanded

            // 获取有效行数据（两种方式任选其一）
            // 方式1：从表格数据源直接获取（推荐）
            const validRows = this.departmentRef.data

            // 方式2：过滤 treeData
            // const rawData = toRaw(this.departmentRef.store.states.treeData)
            // const validRows = Object.values(rawData).filter(item => item?.id)

            nextTick(() => {
                validRows.forEach(row => {
                    if (row?.id) { // 关键检查
                        this.departmentRef.toggleRowExpansion(row, this.isExpanded)
                    }
                })
            })

            localStorage.setItem('departmentlist', this.isExpanded.toString())
        }
    },
    getters: {
        getCollapse() {

        }
    },
}
)